#!/bin/bash

# Define ProxySQL version
PROXYSQL_VERSION="2.5.5-1"

# Detect the operating system
OS=""
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    OS="linux"
elif [[ "$OSTYPE" == "darwin"* ]]; then
    OS="mac"
else
    echo "Unsupported operating system: $OSTYPE"
    exit 1
fi


# Detect the Linux distribution
DISTRO=""
if [ -f "/etc/os-release" ]; then
    DISTRO=$(cat /etc/os-release | grep -oP '(?<=^ID=).*' | tr -d '"')
fi

# Download and install ProxySQL
if [ "$OS" == "linux" ]; then
    checkCommands
    if [ -x "$(command -v dpkg)" ]; then
        # Debian-based Linux installation
        wget https://github.com/sysown/proxysql/releases/download/v${PROXYSQL_VERSION}/proxysql_${PROXYSQL_VERSION}-debian9_amd64.deb
        dpkg -i proxysql_${PROXYSQL_VERSION}-debian9_amd64.deb
        rm proxysql_${PROXYSQL_VERSION}-debian9_amd64.deb
    elif [ -x "$(command -v rpm)" ]; then
        # RedHat-based Linux installation
        # wget https://github.com/sysown/proxysql/releases/download/v${PROXYSQL_VERSION}/proxysql-${PROXYSQL_VERSION}-2.x86_64.rpm
        yum install -y automake bzip2 cmake make gcc-c++ gcc git openssl openssl-devel gnutls gnutls-devel libtool patch libuuid-devel perl-DBD* perl-DBI*
        rpm -ivh source/proxysql-${PROXYSQL_VERSION}-centos7.x86_64.rpm
        rm proxysql-${PROXYSQL_VERSION}-2.x86_64.rpm
    else
      if [ "$DISTRO" == "ubuntu" ]; then
              # Ubuntu installation
              apt-get update
              apt-get install -y proxysql
              systemctl start proxysql
              echo "systemctl start proxysql"
              exit 1
      elif [ "$DISTRO" == "amzn" ]; then
              # Amazon Linux installation
              wget https://github.com/sysown/proxysql/releases/download/v${PROXYSQL_VERSION}/proxysql-${PROXYSQL_VERSION}-2.amzn2.x86_64.rpm
              rpm -Uvh proxysql-${PROXYSQL_VERSION}-2.amzn2.x86_64.rpm
              rm proxysql-${PROXYSQL_VERSION}-2.amzn2.x86_64.rpm
      fi
        echo "Unsupported package manager."
        exit 1
    fi
elif [ "$OS" == "mac" ]; then
    # macOS installation
    brew install proxysql
else
    echo "Unsupported operating system: $OS"
    exit 1
fi



# Check ProxySQL service status
if [ "$OS" == "linux" ]; then
    # Start ProxySQL
    service proxysql start
    if systemctl is-active --quiet proxysql; then
        echo | ps aux | grep proxysql | awk '{print $2}' > source/install.lock
        echo "ProxySQL $PROXYSQL_VERSION has been installed and started."
    else
        echo "ProxySQL installation failed or service did not start."
    fi
elif [ "$OS" == "mac" ]; then
    if brew services list | grep -q "proxysql"; then
        echo "ProxySQL $PROXYSQL_VERSION has been installed and started."
    else
        echo "ProxySQL installation failed or service did not start."
    fi
fi

